var btnId;
var items;
var monitorRecvList;
var monitorSendList;
var monitorObjectList;
var flag = false;

Date.prototype.format = function(format)
{
    var o = {
	"M+" : this.getMonth() + 1, // month
	"d+" : this.getDate(), // day
	"h+" : this.getHours(), // hour
	"m+" : this.getMinutes(), // minute
	"s+" : this.getSeconds(), // second
	"q+" : Math.floor((this.getMonth() + 3) / 3), // quarter
	"S" : this.getMilliseconds()
	}
	if (/(y+)/.test(format))
		format = format.replace(RegExp.$1, (this.getFullYear() + "")
				.substr(4 - RegExp.$1.length));
	for ( var k in o)
		if (new RegExp("(" + k + ")").test(format))
			format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k]
					: ("00" + o[k]).substr(("" + o[k]).length));
	return format;
}

$(document).ready(function() {
	btnId = $("#currentNode").val();
	$("#refreshID").val(btnId);
	$("#default-buttons p button").click(function(){
		if (flag == true) {
			ui.msg("您的操作过于频繁，请5秒后再试！");
			return;
		}
		if(btnId != this.id){
			$("#" + btnId).removeClass("btn-white").addClass("btn-primary");
 			$("#" + this.id).removeClass("btn-primary").addClass("btn-grey");
 			loaderMessage("monitorObjectList");
 			btnId = this.id;
 			$("#refreshID").val(btnId);
			monitorData(this.id);
			$("#" + this.id).checked = false;
		}
	});
	$("#" + btnId).removeClass("btn-primary").addClass("btn-grey");
	showData();
});

function loaderMessage(nodeId){
	var ajaxLoading = '<center><img src="' + _ctx + '/static/images/ajax-loader.gif"></center>';
	$('#' + nodeId).html(ajaxLoading);
}

function showData(){	
	var dateTime = new Date();
	$("#dateTime").text(dateTime.format("yyyy-MM-dd hh:mm:ss"));
	var  nodeCode = btnId;
	loaderMessage("monitorObjectList");
	monitorData(nodeCode);
	setTimeout(showData, 10*60*1000);
}

function monitorData(nodeCode) {
	flag = true;
	$.ajax({
		type : "GET",
		dataType : "json",
		cache : false,
		url : _ctx + "/data_exch_monitor/monitor_list.do?nodeCode="+nodeCode,
		success : function(data) {
			var listObject = data.listObject;
			monitorObjectList = data.monitorObjectList;
			if (listObject.code.trim() == '0000') {
				items = listObject.items;
			}
			$("#" + nodeCode).removeClass("btn-grey").addClass("btn-white");
			monitorRecvList = data.recvList;
			monitorSendList = data.sendList;
			//判断选中的是哪个节点
			selectNode(nodeCode);
			flag = false;
			if(monitorRecvList != null){
				monitorList('recv');
			}
			if(monitorSendList != null){
				monitorList('send');
			}
		}
	});
}

function selectNode(nodeCode) {
   if(monitorObjectList ==''){
	   if($("#currentNode").val() == btnId){
		   var warning = '<font color="red"> 【提示】：监控对象未注册，请先注册监控对象。</font>';
		   $('#monitorObjectList').html(warning);
		   return; 
	   }
   }
   var tiCount = 0;
   var itemsRow = (items.length/3)*3<items.length ? items.length/3+1:items.length/3;
   if (itemsRow == 0) {
	   var warning = '<font color="red"> 【提示】：该节点暂无监控结果数据。</font>';
	   $('#monitorObjectList').html(warning);
	   return; 
   }
   $('#monitorObjectList').html("");
   items.sort(function(a,b){
	   return eval('(' + a.nodeStatus + ')').monitorObject.sort > eval('(' + b.nodeStatus + ')').monitorObject.sort ? 1 :-1;
   });
   for(var i = 0;i < itemsRow;i++){
	  var $row = $("<div class='row'></div>");
	  var start = i*3,end=start + 3 > items.length? items.length:start + 3;
	  var imageType = '';
	  for(var j = start;j < end; j++){
		  if (items[j].nodeCode.trim() == nodeCode.trim()) {
			  var nodeStatus = eval('(' +items[j].nodeStatus + ')');
			  var monitorResult = nodeStatus.monitorResult;
			  var temp = eval('(' +nodeStatus.monitorObject.configParameters + ')');
			  var title = "";
			  if(items[j].objectType == 1){
				  imageType = 'fa-database';
				  title = temp.dbAlias;
				  var objectType = '${app:objectType(1)}';
				  var status = monitorResult.status == 'true' ? '<span style="font-family: verdana;">正常</span>'
							: '<span style="font-family: verdana; color: red">异常</span>';
				  var spaceStatus;
			      if (temp.userSpace <= 10) {
					spaceStatus = '<span style="font-family: verdana;">正常</span>'
				  } else {
					spaceStatus = '<span style="font-family: verdana; color: red">不足</span>';
				  }
				  var $ul = $("<ul style='margin-left: 10px;'></ul>");
				  var $li1 = $("<li>[数据库类型]：" + temp.dbType + "</li>"),
			          $li2 = $("<li>[链接地址]：" + temp.url + "</li>"),
			          $li3 = $("<li>[用户名]：" + temp.userName + "</li>");
					  $ul.append($li1);
					  $ul.append($li2);
					  $ul.append($li3); 
				  //有dba权限	  
				  if(temp.ifDba =='1'){
					  if(monitorResult.status == 'true'){
						  var $li4 = $("<li>[表空间]：" + spaceStatus + ":<a href='javascript:void(0);' onclick='gettsInfo(\"" + temp.dbType + "\",\"" + temp.url + "\",\"" + temp.userName + "\",\"" + temp.password + "\")'><img src='" + _ctx + "/static/images/view.png' width='15px' title='查看'/></a></li>"),
						      $li5 = $("<li>[内存大小]：" + monitorResult.totalMemory.toFixed(0) + "M</li>"),
						      $li6 = $("<li>[最大连接数]：" + monitorResult.maxProcesses + " 个&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;当前连接数："+monitorResult.currentProcess+" 个  <a href='javascript:void(0);' onclick='getCpInfo(\"" + temp.dbType + "\",\"" + temp.url + "\",\"" + temp.userName + "\",\"" + temp.password + "\")'><img src='" + _ctx + "/static/images/view.png' width='15px' title='查看'/></a><BR></li>"); 
							  $ul.append($li4);
							  $ul.append($li5);
							  $ul.append($li6);
					  }
					  else
					  {
						  var db_Message = "";
						  var $li5 = "";
						  if (monitorResult.msg == 'DB_CODE_00000') {
							db_Message = "网络连接失败";
						  } else if (monitorResult.msg == 'DB_CODE_00001') {
							db_Message = "用户名/密码错误";
						  } else if (monitorResult.msg == 'DB_CODE_00002') {
							db_Message = "该账户已锁定";
						  }else if(monitorResult.msg == 'DB_CODE_00003'){
							  db_Message = "监听程序无法识别连接描述符中请求的服务";
						  }
						  var $li4 = $("<li>[状态]：" + status + "</li>");
						  if(db_Message != ""){
							  $li5 = $("<li>[信息]：" + db_Message + "</li>");
						  }else{
							  $li5 = $("<BR>");
						  }
						  $li6 = $("<BR>");
						  $ul.append($li4);
						  $ul.append($li5);
						  $ul.append($li6);
					  }
				  }else{
					  var $li4 = $("<BR>"),
					  $li5 = $("<BR>");
				  	  $li6 = $("<BR>");
					  $ul.append($li4);
					  $ul.append($li5);
					  $ul.append($li6);
				  }	  
				  
			  }else if(items[j].objectType == 2 && tiCount == 0){
				  imageType = 'fa-link';
				  title = temp.tiName;
				  var objectType = '${app:objectType(1)}';
				  var interStatus = monitorResult.interStatus == 'true' ? '<span style="font-family: verdana;">正常</span>'
					  : '<span style="font-family: verdana; color: red">异常</span>';
				  var logStatus = monitorResult.logStatus == 'true' ? '<span style="font-family: verdana;">正常</span>'
					  : '<span style="font-family: verdana; color: red">异常</span>';
				  var $ul = $("<ul></ul>");
				  var $li1 = $("<li>[服务器IP]：" + temp.tiIp + "</li>"),
			          $li2 = $("<li>[配置文件路径]：" + temp.cfgFilePath + "</li>"),
			          $li3 = $("<li>[任务日志路径]：" + temp.tiLogPath + "</li>");
				  	  $li4 = $("<li>[运行任务总数]：" + monitorResult.taskNum + " <a href='javascript:void(0);' onclick='getTiInfo(\"" + btnId + "\")')><img src='" + _ctx + "/static/images/view.png' width='15px' title='查看'/></a></li>"),
				      $li5 = $("<li>[网络通讯状态]：" + interStatus + "</li>"),
				      $li6 = $("<li>[日志监控状态]：" + logStatus + "<BR></li>");
					  $ul.append($li1);
					  $ul.append($li2);
					  $ul.append($li3); 
					  $ul.append($li4);
					  $ul.append($li5);
					  $ul.append($li6);
					  tiCount++;
					  console.warn();
			  } else if (items[j].objectType == 3) {
				  imageType = 'fa-ship';
				  title = temp.jeeName;
				  var temp = eval('(' + nodeStatus.monitorObject.configParameters + ')');
				  var monitorResult = nodeStatus.monitorResult;
				  var status = monitorResult.status == 'true' ? '<span style="font-family: verdana;">正常</span>'
						  : '<span style="font-family: verdana; color: red">异常</span>';
				  var $ul = $("<ul></ul>");
				  if(monitorResult.status =='true'){
					  var $li1 = $("<li>[类型]：" + monitorResult.containerType + "&nbsp;&nbsp;&nbsp;&nbsp;JMX：" + temp.jeeIp + ":" + temp.jeePort + "</li>"),
				  	  $li2 = $("<li>[系统]：" + monitorResult.systemName + "&nbsp;&nbsp;&nbsp;&nbsp;CPU：" + monitorResult.cpu + "&nbsp;&nbsp;个</li>");
				      $li3 = $("<li>[内存]：物理内存：" + "共" + monitorResult.memorySize + "G&nbsp;&nbsp;剩" + monitorResult.memoryFreeSize + "G&nbsp;&nbsp;虚拟内存：共" + monitorResult.virtualMemorySize + "G</li>"); 
			          $li4 = $("<li>[JDK]：" + monitorResult.javaVersion + "</li>");
				  	  $li5 = $("<li>[JVM]：" + monitorResult.jvm + monitorResult.jvmHeapMemoryUsed + "<BR>" + monitorResult.jvmNoHeapMemoryUsed + "GC：" + monitorResult.gc + " 次&nbsp;&nbsp;线程总数" + monitorResult.threadTotal +"&nbsp;&nbsp;守护线程：" + monitorResult.threadGuard + "</li>");
					  $ul.append($li1);
					  $ul.append($li2);
					  $ul.append($li3); 
					  $ul.append($li4);
					  $ul.append($li5);
				  }else{
					  var $li1 = $("<li>[类型]：" + temp.containerType + "</li>"),
				  	  $li2 = $("<li>[服务器地址]：" + temp.jeeIp + ":" + temp.jeePort + "</li>");
					  var msg;
					  if(monitorResult.msg.indexOf("ConnectException") != -1){
						  msg = '<span style="font-family: verdana; color: red">连接异常</span>';
						  $li3 = $("<li>[服务器状态]：" + msg + "</li>"); 
					  }else{
						  $li3 = $("<li>[服务器状态]：异常</li>"); 
					  }
			          $li4 = $("<BR>");
				  	  $li5 = $("<BR>");
				  	  $li6 = $("<BR>");
					  $ul.append($li1);
					  $ul.append($li2);
					  $ul.append($li3); 
					  $ul.append($li4);
					  $ul.append($li5);
					  $ul.append($li6);
				  }
				 
			}
		  var $col=$("<div class='col-sm-4'><div class='panel panel-primary'>" +
				  "<div class='panel-heading'><i class='fa "+imageType+" fa-lg'></i>&nbsp;&nbsp;" + title + "</div>" +
				  "<div class='row'><div class='col-xs-12'><div class='profile-user-info' style='padding-left: 10px;'>" + $ul.html() + "</div></div></div>"+
		  "</div></div>");
		  $row.append($col);
		  }
	  }
	  $('#monitorObjectList').append($row);
   }
}
function monitorList(type) {
	var list;
	var colNm1;
	var colNm2;
	var sendOrRecv;
	if (type == 'recv') {
		sendOrRecv = '发送节点';
		colNm1 = '节点实发';
		colNm2 = '中央实收';
	} else {
		sendOrRecv = '接收节点';
		colNm1 = '中央实发';
		colNm2 = '节点实收';
	}
	var content = '<div class="table-responsive" >'
			+ '<table class="table table-striped table-bordered table-hover">'
			+ '<tr>'
			+ '<th rowspan="2" style="vertical-align: middle;">'
			+ sendOrRecv
			+ '</th>'
			+ '<th colspan="2">雨水情监测数据</th>'
			+ '<th colspan="2">取用水监测数据</th>'
			+ '<th colspan="2">水质监测数据</th>'
			+ '<th colspan="2">水功能区评价数据</th>'
			+ '<th colspan="2">水质评价数据</th>'
			+ '<th colspan="2">统一用户数据</th>'
			+ '<th colspan="2">基础数据</th>'
			+ '</tr>'
			+ '<tr>'
			+ '<td align="center">'
			+ colNm1
			+ '</td>'
			+ '<td align="center">'
			+ colNm2
			+ '</td>'
			+ '<td align="center">'
			+ colNm1
			+ '</td>'
			+ '<td align="center">'
			+ colNm2
			+ '</td>'
			+ '<td align="center">'
			+ colNm1
			+ '</td>'
			+ '<td align="center">'
			+ colNm2
			+ '</td>'
			+ '<td align="center">'
			+ colNm1
			+ '</td>'
			+ '<td align="center">'
			+ colNm2
			+ '</td>'
			+ '<td align="center">'
			+ colNm1
			+ '</td>'
			+ '<td align="center">'
			+ colNm2
			+ '</td>'
			+ '<td align="center">'
			+ colNm1
			+ '</td>'
			+ '<td align="center">'
			+ colNm2
			+ '</td>'
			+ '<td align="center">'
			+ colNm1
			+ '</td>'
			+ '<td align="center">' + colNm2 + '</td>' + '</tr>';
	var nodeNm;
	if (type == 'recv') {
		list = monitorRecvList;
	} else {
		list = monitorSendList;
	}
	if (list.length == 0) {
		return;
	}
	for ( var i = 0; i < list.length; i++) {
		if (type == 'recv') {
			//nodeNm = '${ni:getNodeName("'+list[i].slszyNode+'")}';
			nodeNm = list[i].slszyNm;
		} else {
			//nodeNm = '${ni:getNodeName("'+list[i].dstNode+'")}';
			nodeNm = list[i].dstNm;
		}
		content = content + '<tr><td>' + nodeNm + '</td>' + '<td>'
				+ list[i].rainMonitorSend + '</td>' + '<td>'
				+ list[i].rainMonitorRecv + '</td>' + '<td>'
				+ list[i].userMonitorSend + '</td>' + '<td>'
				+ list[i].userMonitorRecv + '</td>' + '<td>'
				+ list[i].waterQMonitorSend + '</td>' + '<td>'
				+ list[i].waterQMonitorRecv + '</td>' + '<td>'
				+ list[i].waterREvaluateSend + '</td>' + '<td>'
				+ list[i].waterREvaluateRecv + '</td>' + '<td>'
				+ list[i].waterQEvaluateSend + '</td>' + '<td>'
				+ list[i].waterQEvaluateRecv + '</td>' + '<td>'
				+ list[i].uumsSend + '</td>' + '<td>' + list[i].uumsRecv
				+ '</td>' + '<td>' + list[i].baseSend + '</td>' + '<td>'
				+ list[i].baseRecv + '</td></tr>';
	}
	if (type == 'recv') {
		$('#monitorRecv').replaceWith(content);
		//replaceWith()
	} else {
		$('#monitorSend').replaceWith(content);
	}
}

function button() {
	$("th").removeAttr("text-align");
	$(".img-style").hover(function() {
		var content = $(this).attr("alt");
		if (content == "red") {
			$(".img-style").attr("title", "非正常");
		} else {
			$(".img-style").attr("title", "正常");
		}
	});
	var d1 = [];
	for ( var i = 0; i < Math.PI * 2; i += 0.5) {
		d1.push([ i, Math.sin(i) ]);
	}

	var d2 = [];
	for ( var i = 0; i < Math.PI * 2; i += 0.5) {
		d2.push([ i, Math.cos(i) ]);
	}

	var d3 = [];
	for ( var i = 0; i < Math.PI * 2; i += 0.2) {
		d3.push([ i, Math.tan(i) ]);
	}

	var sales_charts = $('#sales-charts').css({
		'width' : '100%',
		'height' : '100px'
	});
	$.plot("#sales-charts", [ {
		label : "Domains",
		data : d1
	}, {
		label : "Hosting",
		data : d2
	}, {
		label : "Services",
		data : d3
	} ], {
		hoverable : true,
		shadowSize : 0,
		series : {
			lines : {
				show : true
			},
			points : {
				show : true
			}
		},
		xaxis : {
			tickLength : 0
		},
		yaxis : {
			ticks : 6,
			min : -1,
			max : 1,
			tickDecimals : 3
		},
		grid : {
			backgroundColor : {
				colors : [ "#fff", "#fff" ]
			},
			borderWidth : 1,
			borderColor : '#555'
		}
	});
}

function gettsInfo(dbType,url,userName,password) {
	$.ajax({
		type : "GET",
		dataType : "html",
		cache : false,
		url : _ctx + '/data_exch_monitor/monitor_get_tablespace_info.do?dbType='+ dbType +'&url='+url+'&userName='+userName+'&password='+password,
		success : function(content) {
			$('#monitorGetDiv').html(content);
			$('#monitorGetModal').modal('show');
		},
		error : function() {
			ui.msg('查看表空间信息失败！', 0);
		}
	});
}

function getTiInfo(btnId) {
	$.ajax({
		type : "GET",
		dataType : "html",
		cache : false,
		url : _ctx + '/data_exch_monitor/monitor_get_ti_info.do?slszyNode='+ btnId,
		success : function(content) {
			$('#monitorGetTiDiv').html(content);
			$('#monitorGetTiModal').modal('show');
		},
		error : function() {
			ui.msg('查看TI任务失败！', 0);
		}
	});
}
function getCpInfo(dbType,url,userName,password) {
	$.ajax({
		type : "GET",
		dataType : "html",
		cache : false,
		url : _ctx + '/data_exch_monitor/monitor_get_curprocess_info.do?dbType='+ dbType +'&url='+url+'&userName='+userName+'&password='+password,
		success : function(content) {
			$('#monitorGetCpDiv').html(content);
			$('#monitorGetCpModal').modal('show');
		},
		error : function() {
			ui.msg('查看当前连接数详细信息失败！', 0);
		}
	});
}
